package middleware

import (
	"RocFamilySystem/pkg/constant"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"runtime"
	"strings"
)

func HandleErr() gin.HandlerFunc {

	return func(ctx *gin.Context) {
		defer func() {
			_, file, line, _ := runtime.Caller(4)
			err := recover()
			if err == nil {
				return
			}
			if errConvert, ok := err.(error); ok {
				err = errConvert.Error()
			}
			fmt.Printf("\n%s:%d\t 错误：%s", file, line, err)
			if strings.Trim(err.(string), "\n") == constant.AUTHORITY_ERROR {
				ctx.JSON(http.StatusOK, gin.H{
					"code": 401,
					"msg":  err,
				})
			} else {
				ctx.JSON(http.StatusOK, gin.H{
					"code": 500,
					"msg":  err,
				})
			}
			ctx.Abort()
		}()
		ctx.Next()

	}
}
